# -*- coding: utf-8 -*-

# Author: 一根鱼骨棒
# Date: 2021-03-18 15:57:58
# LastEditTime: 2021-06-04 10:19:19
# LastEditors: 一根鱼骨棒
# Description: 本开源代码使用GPL 3.0协议
# symbol_custom_string_obkoro1: Software: VScode
# symbol_custom_string_obkoro10001: Copyright 2021 迷舍

import csv
import json
import time
from datetime import datetime

import matplotlib as mpl
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import pandas as pd
import requests
from IPython.display import HTML
from matplotlib import cm

time_stamp = int(time.time())
url = f"https://web-api.coinmarketcap.com/v1/cryptocurrency/ohlcv/historical?convert=USD&slug=bitcoin&time_end={time_stamp}&time_start=1367107200"
rd = requests.get(url=url)
# 返回的数据是 JSON 格式，使用 json 模块解析
co = json.loads(rd.content)
list1 = co['data']['quotes']
with open('BTC.csv', 'w', encoding='utf8', newline='') as f:
    csvi = csv.writer(f)
    csv_head = ["date", "price", "volume"]
    csvi.writerow(csv_head)
    for i in list1:
        quote_date = i["time_open"][:10]
        quote_price = "{:.2f}".format(i["quote"]["USD"]["close"])
        quote_volume = "{:.2f}".format(i["quote"]["USD"]["volume"])
        csvi.writerow([quote_date, quote_price, quote_volume])

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.rc('axes', axisbelow=True)
mpl.rcParams['animation.embed_limit'] = 2**128
df = pd.read_csv('BTC.csv')
df['date']=[datetime.strptime(d, '%Y-%m-%d').date() for d in df['date']]
Span_Date =180
Num_Date =360 #终止日期
df_temp=df.loc[Num_Date-Span_Date: Num_Date,:] #选择从Num_Date-Span_Date开始到Num_Date的180天的数据
colors = cm.Spectral_r(df_temp.price / float(max(df_temp.price)))
fig =plt.figure(figsize=(6,4), dpi=100)
plt.subplots_adjust(top=1,bottom=0,left=0,right=0.9,hspace=0,wspace=0)
plt.bar(df_temp.date.values,df_temp.price.values,color=colors,width=1,align="center",zorder=1)
plt.plot(df_temp.date, df_temp.price, color='k',zorder=2)
plt.scatter(df_temp.date.values[-1], df_temp.price.values[-1], color='white',s=150,edgecolor ='k',linewidth=2,zorder=3)
plt.text(df_temp.date.values[-1], df_temp.price.values[-1]*1.18,s=np.round(df_temp.price.values[-1],1),size=10,ha='center', va='top')
plt.ylim(0, df_temp.price.max()*1.68)
plt.xticks(ticks=df_temp.date.values[0: Span_Date +1:30],labels=df_temp.date.values[0: Span_Date +1:30],rotation=0)
plt.margins(x=0.01)
ax = plt.gca()#边框 
ax.spines['top'].set_color('none') # 设置上‘脊梁’为无色
ax.spines['right'].set_color('none') # 设置上‘脊梁’为无色
ax.spines['left'].set_color('none') # 设置上‘脊梁’为无色
plt.grid(axis="y",c=(217/256,217/256,217/256),linewidth=1) #设置网格线
plt.show()